package com.ems.servlet;

import com.ems.dao.DepartmentDAO;
import com.ems.dao.EmployeeDAO;
import com.ems.dao.UserDAO;
import com.ems.model.Department;
import com.ems.model.Employee;
import com.ems.model.User;
import com.ems.util.PasswordUtil;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            EmployeeDAO employeeDAO = new EmployeeDAO();
            DepartmentDAO departmentDAO = new DepartmentDAO();
            UserDAO userDAO = new UserDAO();

            if ("add".equals(action)) {
                // 添加新员工
                Employee emp = createEmployeeFromRequest(request);

                if (employeeDAO.addEmployee(emp)) {
                    // 自动创建员工账号
                    User user = new User();
                    user.setUserId(emp.getEmpId());
                    user.setUsername(emp.getName());
                    user.setPassword(PasswordUtil.hashPassword("123456")); // 初始密码
                    user.setRole("employee");

                    userDAO.addUser(user);

                    response.sendRedirect("employee?action=list");
                    return;
                } else {
                    request.setAttribute("error", "添加员工失败");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                    dispatcher.forward(request, response);
                }
            } else if ("update".equals(action)) {
                // 更新员工信息
                Employee emp = createEmployeeFromRequest(request);

                if (employeeDAO.updateEmployee(emp)) {
                    response.sendRedirect("employee?action=list");
                } else {
                    request.setAttribute("error", "更新员工信息失败");
                    // 修复：失败时保留员工信息和部门信息
                    request.setAttribute("employee", emp);
                    request.setAttribute("departments", departmentDAO.getAllDepartments());

                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee_edit.jsp");
                    dispatcher.forward(request, response);
                }
            } else if ("delete".equals(action)) {
                // 删除员工
                String empId = request.getParameter("empId");

                if (employeeDAO.deleteEmployee(empId)) {
                    // 同时删除用户账号
                    userDAO.deleteUser(empId);
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                    dispatcher.forward(request, response);
                } else {
                    request.setAttribute("error", "删除员工失败");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                    dispatcher.forward(request, response);
                }
            } else if ("search".equals(action)) {
                String keyword = request.getParameter("keyword");
                List<Employee> employees = employeeDAO.searchEmployees(keyword);
                request.setAttribute("employees", employees);

                // 添加部门数据
                List<Department> departments = departmentDAO.getAllDepartments();
                request.setAttribute("departments", departments);

                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                dispatcher.forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "操作失败，请稍后再试");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
            dispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("getEmployeeName".equals(action)) {
            String empId = request.getParameter("empId");
            try {
                EmployeeDAO dao = new EmployeeDAO();
                Employee emp = dao.getEmployeeById(empId);
                if (emp != null) {
                    response.setContentType("text/plain");
                    response.getWriter().write(emp.getName());
                } else {
                    response.getWriter().write("");
                }
            } catch (Exception e) {
                response.getWriter().write("");
            }
            return;
        }
        try {
            EmployeeDAO employeeDAO = new EmployeeDAO();
            DepartmentDAO departmentDAO = new DepartmentDAO();

            if ("list".equals(action)) {
                // 列出所有员工
                List<Employee> employees = employeeDAO.getAllEmployees();
                request.setAttribute("employees", employees);
                request.setAttribute("departments", departmentDAO.getAllDepartments());
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                dispatcher.forward(request, response);
            } else if ("view".equals(action)) {
                // 查看单个员工详情
                String empId = request.getParameter("empId");
                Employee employee = employeeDAO.getEmployeeById(empId);
                request.setAttribute("employee", employee);
                request.setAttribute("departments", departmentDAO.getAllDepartments());
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                dispatcher.forward(request, response);
            } else if ("edit".equals(action)) {
                // 编辑员工信息
                String empId = request.getParameter("empId");
                Employee employee = employeeDAO.getEmployeeById(empId);

                if (employee != null) {
                    request.setAttribute("employee", employee);
                    request.setAttribute("departments", departmentDAO.getAllDepartments());

                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee_edit.jsp");
                    dispatcher.forward(request, response);
                } else {
                    request.setAttribute("error", "找不到该员工信息");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
                    dispatcher.forward(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "操作失败");
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/employee.jsp");
            dispatcher.forward(request, response);
        }
    }

    private Employee createEmployeeFromRequest(HttpServletRequest request) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Employee emp = new Employee();
        // 修复：确保 empId 正确设置
        if (request.getParameter("empId") != null) {
            emp.setEmpId(request.getParameter("empId"));
        }
        emp.setEmpId(request.getParameter("empId"));
        emp.setName(request.getParameter("name"));
        emp.setGender(request.getParameter("gender"));
        emp.setNation(request.getParameter("nation"));
        emp.setBirthplace(request.getParameter("birthplace"));
        emp.setBirthday(new Date(sdf.parse(request.getParameter("birthday")).getTime()));
        emp.setEmail(request.getParameter("email"));
        emp.setPhone(request.getParameter("phone"));
        emp.setAddress(request.getParameter("address"));
        emp.setDeptId(Integer.parseInt(request.getParameter("deptId")));
        emp.setPosition(request.getParameter("position"));
        emp.setSalary(Double.parseDouble(request.getParameter("salary")));
        emp.setEducation(request.getParameter("education"));
        emp.setGraduateSchool(request.getParameter("graduateSchool"));
        emp.setHireDate(new Date(sdf.parse(request.getParameter("hireDate")).getTime()));
        emp.setStatus(request.getParameter("status"));
        emp.setContractId(request.getParameter("contractId"));

        String regularDate = request.getParameter("regularDate");
        if (regularDate != null && !regularDate.isEmpty()) {
            emp.setRegularDate(new Date(sdf.parse(regularDate).getTime()));
        } else {
            emp.setRegularDate(null);
        }

        String leaveDate = request.getParameter("leaveDate");
        if (leaveDate != null && !leaveDate.isEmpty()) {
            emp.setLeaveDate(new Date(sdf.parse(leaveDate).getTime()));
        } else {
            emp.setLeaveDate(null);
        }

        return emp;
    }
}